Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [123]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

###### define function to load train, test, and validation datasets ######
# keras.utils.to_categorical(y, num_classes=None)
# Converts a class vector (integers) to binary class matrix.
# y: class vector to be converted into a matrix (integers from 0 to num_classes).
# num_classes: total number of classes.
# Returns a binary matrix representation of the input.
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are {0} total dog categories.'.format(len(dog_names)))
#print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
#print('There are {0} total dog images.\n'.format(len(np.hstack([train_files, valid_files, test_files]))))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))

#print(dog_names)
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [64]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))      # /*/* = Load everything that's in the lfw folder
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [65]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

###### extract pre-trained face detector ######
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[2])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray, scaleFactor = 1.1)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [66]:
# returns "True" if face is detected by the face_cascade function in image stored at img_path.
def face_detector(img_path, face_cascade):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor = 1.1)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

98% of the human pictures are detected as humans.

1% of the dog pictures are detected as humans.

In [67]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.
import time

# Take the time
start = time.time()

def perfTest(a_face_detector, face_cascade):
    ## TODO: Test the performance of the face_detector algorithm 
    ## on the images in human_files_short and dog_files_short.
    human_detected_as_human = 0
    human_detected_as_dog = 0
    for i in range(100):
        if a_face_detector(human_files_short[i], face_cascade):
            human_detected_as_human += 1
        elif a_face_detector(dog_files_short[i], face_cascade):
            human_detected_as_dog += 1
            
    print("Percentage of human faces detected among the first 100 human pictures: {0}% "
          .format(human_detected_as_human/len(human_files_short)*100))
    print("Percentage of human faces detected among the first 100 dog pictures: {0}% "
          .format(human_detected_as_dog/len(dog_files_short)*100))

#Print the performance   
perfTest(face_detector, face_cascade)

# Total time
end = time.time()
print("Total time taken to detect the faces: {0:0.2f}s".format(end-start))
Percentage of human faces detected among the first 100 human pictures: 98.0% 
Percentage of human faces detected among the first 100 dog pictures: 1.0% 
Total time taken to detect the faces: 7.70s

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

Well, as far as I know, that is usually a quite normal approach to take. Normally we as users are asked to upload a picture where the face can be identified quite clearly. I dont find the expectations to be too hight to set. Besides that, uploading a picture in profile would maybe make less of a sence for example. However, it would be cool to be able to do so in a gaming or just-for-fun app. Just as we did on the CIFAR-10 database pictures, adding reshaped pictures through augmentation and have our algorithm train on those as well might increase to probability to detect less clear ones. Considering shapes and outlines of a face could also increase the reliability (the differences in the shape of the face is quite distinct for humans and dogs). Also, taking into account that the size of the face can vary might increase the hit rate.

However, Haar cascades seems to be a good approach and turns out to be one of the better ones out there. And its free.

Comparing Haar cascades with the LBP cascade below, we see that the latter is more than twice as fast as Haar, but with worse accuracy. One application area might be a toy app for phones where speed might be of more importance for the user.


We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [68]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

# extract pre-trained and downloaded face detector #
face_cascade2 = cv2.CascadeClassifier('lbpcascade/lbpcascade_frontalface_improved.xml')

# load color (BGR) image
img2 = cv2.imread(human_files[2])
# convert BGR image to grayscale
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

# find faces in image
faces2 = face_cascade2.detectMultiScale(gray2, scaleFactor = 1.2)

# print number of faces detected in the image
print('Number of faces detected:', len(faces2))

# get bounding box for each detected face
for (x,y,w,h) in faces2:
    # add bounding box to color image
    cv2.rectangle(img2,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb2)
plt.show()

# Take the time
start = time.time()

# Print some statistics  
perfTest(face_detector, face_cascade2)

# Total time
end = time.time()
print("Total time taken to detect the faces: {0:0.2f}s".format(end-start))
Number of faces detected: 0
Percentage of human faces detected among the first 100 human pictures: 89.0% 
Percentage of human faces detected among the first 100 dog pictures: 1.0% 
Total time taken to detect the faces: 3.53s

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [69]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [70]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    # (The fourth axis (from 3D to 4D) is added at position axis=0)
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [71]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [72]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

1% of the humans (in human_files_short) are detected as dogs.

99% of the dogs (in dog_files_short) are detected as dogs.

In [12]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

start = time.time()

human_detected_as_dog = 0
dog_detected_as_dog = 0
for i in range(len(human_files_short)):
    if dog_detector(human_files_short[i]):
        human_detected_as_dog += 1
    elif dog_detector(dog_files_short[i]):
        dog_detected_as_dog += 1

print("Percentage of humans detected as dogs: {0}%".format(human_detected_as_dog*100/len(human_files_short)))
print("Percentage of dogs detected as dogs: {0}%".format(dog_detected_as_dog*100/len(dog_files_short)))  


# Total time
end = time.time()
print("Total time taken to determine the performance: {0:0.2f}s".format(end-start))
Percentage of humans detected as dogs: 1.0%
Percentage of dogs detected as dogs: 99.0%
Total time taken to determine the performance: 103.45s

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [73]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [02:42<00:00, 41.01it/s]
100%|██████████| 835/835 [00:18<00:00, 45.94it/s]
100%|██████████| 836/836 [00:18<00:00, 45.42it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer: First of all, augment the training data resulted in worse results and took longer time to train, so it was excluded. 10 epochs were tested in both cases. The code can be found below, however, the results are not shown.

The first layer in the CNN must have an input shape of (None, 224, 224, 3) to match the input data we provide it with. The input data constitutes of colour pictures, with the size of 224x224 pixels. Choosing a Conv2D layer with 16 filters to start with, increases the depth of the CNN. From our experience earlier, in the CIFAR-10 database, we know that choosing padding='same' and the activation function='relu' gives us acceptable results (at least sufficient to exceed 1% accuracy), so let's try that again. (Also, it is said in the video that this combination often yields the best results. Given that strides=1.) Adding a MaxPooling2D layer afterwards will decrease the risk of overfitting by reducing the feature map (or spatial dimensions) by half (pool_size=2). I find the GlobalAveragePooling2D layer to reduce the feature map too much, why I choose the MaxPooling2D instead.

Adding another Conv2D layer afterwards and increasing its depth gradually to 32 filters seems like a reasonable next step. Using the same padding and activation function as before, would be in accordance to the CNN we used in the CIFAR-10 case. Slicing the spatial dimension by half again, to prevent overfitting, using a MaxPooling2D layer also seems reasonable.

Adding two Conv2D (filters=64 is the only change) and two MaxPooling2D layers on top of this would increase the number of parameters and the depth, while at the same time decrease the spatial dimension in the CNN. I choose two identical layers here and that's basically just to try it out. In the end, we are just interested in finding a CNN that does slightly better than pure chance. Whether this would be ideal to get higher accuracy is hard to tell (given more epochs). Also, having two layers with 64 filters each rather than one with 64 and another with 128 filters reduces the number of parameters amd, thus, decreased the training time.

Second to the last, we add a GlobalAveragePooling2D layer to reduce the dimensianality to a 2D vector. The Dense layer is added last, with an output layer of 133 (we have 133 different dog breeds to choose between). The activation function='softmax' is chosen to give us the output as a probability.

Create and Configure Augmented Image Generator

In [74]:
#from keras.preprocessing.image import ImageDataGenerator

#train_tensors_to_use = train_tensors
#valid_tensors_to_use = valid_tensors

# create and configure augmented image generator
#datagen_train = ImageDataGenerator(
#    width_shift_range=0.2,  # randomly shift images horizontally (20% of total width)
#    height_shift_range=0.2,  # randomly shift images vertically (20% of total height)
#    horizontal_flip=True) # randomly flip images horizontally

# create and configure augmented image generator
#datagen_valid = ImageDataGenerator(
#    width_shift_range=0.2,  # randomly shift images horizontally (20% of total width)
#    height_shift_range=0.2,  # randomly shift images vertically (20% of total height)
#    horizontal_flip=True) # randomly flip images horizontally

# fit augmented image generator on data
#datagen_train.fit(train_tensors_to_use)
#datagen_valid.fit(valid_tensors_to_use)

#train_tensors.shape

Create the CNN Architecture

In [75]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, GlobalMaxPooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
from keras.callbacks import ModelCheckpoint 


model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu', input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu')) 
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(GlobalAveragePooling2D())
model.add(Dense(133, activation='softmax'))   # - 133 different breeds. This is a fully connected layer. 
                                              # One can try to add several to increase the accuracy.
                                              # - Adding Dropouts to curb overfitting
                                              # - Stagging multiple convolutional layers before a single max pool
                                              # might increase the accuracy as well. 
        
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_433 (Conv2D)          (None, 224, 224, 16)      208       
_________________________________________________________________
max_pooling2d_7 (MaxPooling2 (None, 112, 112, 16)      0         
_________________________________________________________________
conv2d_434 (Conv2D)          (None, 112, 112, 32)      2080      
_________________________________________________________________
max_pooling2d_8 (MaxPooling2 (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_435 (Conv2D)          (None, 56, 56, 64)        8256      
_________________________________________________________________
max_pooling2d_9 (MaxPooling2 (None, 28, 28, 64)        0         
_________________________________________________________________
conv2d_436 (Conv2D)          (None, 28, 28, 64)        16448     
_________________________________________________________________
max_pooling2d_10 (MaxPooling (None, 14, 14, 64)        0         
_________________________________________________________________
global_average_pooling2d_3 ( (None, 64)                0         
_________________________________________________________________
dense_4 (Dense)              (None, 133)               8645      
=================================================================
Total params: 35,637.0
Trainable params: 35,637.0
Non-trainable params: 0.0
_________________________________________________________________

Compile the Model

In [76]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [244]:
from keras.callbacks import ModelCheckpoint  
import time

### TODO: specify the number of epochs that you would like to use to train the model.
epochs = 10

# Time the training
start = time.time()

### Do NOT modify the code below this line.
##### - Then how will I be able to use the augmented training data??

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)

#batch_size=20
#model.fit_generator(datagen_train.flow(train_tensors, train_targets, batch_size=batch_size),
#                    steps_per_epoch=train_tensors.shape[0] // batch_size,
#                    epochs=epochs, verbose=2, callbacks=[checkpointer],
#                    validation_data=datagen_valid.flow(valid_tensors, valid_targets, batch_size=batch_size),
#                    validation_steps=valid_tensors.shape[0] // batch_size)



# Print out how long it took to train
end = time.time()
tt = end-start
print()
print("Total training time was {0:0.0f} min and {1:0.0f}s. ".format((tt-tt%60)/60, tt%60))
Train on 6680 samples, validate on 835 samples
Epoch 1/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8868 - acc: 0.0084       Epoch 00000: val_loss improved from inf to 4.87553, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 288s - loss: 4.8868 - acc: 0.0084 - val_loss: 4.8755 - val_acc: 0.0132
Epoch 2/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8720 - acc: 0.0102      Epoch 00001: val_loss improved from 4.87553 to 4.85878, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 278s - loss: 4.8719 - acc: 0.0102 - val_loss: 4.8588 - val_acc: 0.0156
Epoch 3/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8475 - acc: 0.0140      Epoch 00002: val_loss improved from 4.85878 to 4.82511, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 275s - loss: 4.8476 - acc: 0.0139 - val_loss: 4.8251 - val_acc: 0.0108
Epoch 4/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8003 - acc: 0.0183      Epoch 00003: val_loss improved from 4.82511 to 4.78555, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 281s - loss: 4.8005 - acc: 0.0183 - val_loss: 4.7856 - val_acc: 0.0180
Epoch 5/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.7426 - acc: 0.0240  Epoch 00004: val_loss improved from 4.78555 to 4.74387, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 279s - loss: 4.7423 - acc: 0.0240 - val_loss: 4.7439 - val_acc: 0.0168
Epoch 6/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.6920 - acc: 0.0270      Epoch 00005: val_loss improved from 4.74387 to 4.70857, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 283s - loss: 4.6925 - acc: 0.0269 - val_loss: 4.7086 - val_acc: 0.0323
Epoch 7/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.6389 - acc: 0.0320      Epoch 00006: val_loss improved from 4.70857 to 4.65508, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 282s - loss: 4.6382 - acc: 0.0320 - val_loss: 4.6551 - val_acc: 0.0228
Epoch 8/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.5813 - acc: 0.0437  Epoch 00007: val_loss improved from 4.65508 to 4.60911, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 283s - loss: 4.5821 - acc: 0.0436 - val_loss: 4.6091 - val_acc: 0.0395
Epoch 9/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.5210 - acc: 0.0464  Epoch 00008: val_loss improved from 4.60911 to 4.57339, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 285s - loss: 4.5218 - acc: 0.0463 - val_loss: 4.5734 - val_acc: 0.0323
Epoch 10/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.4593 - acc: 0.0492  Epoch 00009: val_loss improved from 4.57339 to 4.52805, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 286s - loss: 4.4598 - acc: 0.0493 - val_loss: 4.5280 - val_acc: 0.0443

Total training time was 47 min and 6s. 

Load the Model with the Best Validation Loss

In [16]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [17]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 5.2632%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [18]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [19]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229.0
Trainable params: 68,229.0
Non-trainable params: 0.0
_________________________________________________________________

Compile the Model

In [20]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [24]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6460/6680 [============================>.] - ETA: 0s - loss: 12.0607 - acc: 0.1300      Epoch 00000: val_loss improved from inf to 10.38129, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 12.0112 - acc: 0.1326 - val_loss: 10.3813 - val_acc: 0.2431
Epoch 2/20
6420/6680 [===========================>..] - ETA: 0s - loss: 9.8448 - acc: 0.2978 Epoch 00001: val_loss improved from 10.38129 to 9.82227, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.8279 - acc: 0.2990 - val_loss: 9.8223 - val_acc: 0.2886
Epoch 3/20
6440/6680 [===========================>..] - ETA: 0s - loss: 9.3163 - acc: 0.3516 Epoch 00002: val_loss improved from 9.82227 to 9.51149, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s - loss: 9.3074 - acc: 0.3525 - val_loss: 9.5115 - val_acc: 0.3114
Epoch 4/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.0304 - acc: 0.3911Epoch 00003: val_loss improved from 9.51149 to 9.34928, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.0105 - acc: 0.3922 - val_loss: 9.3493 - val_acc: 0.3449
Epoch 5/20
6460/6680 [============================>.] - ETA: 0s - loss: 8.8909 - acc: 0.4104 Epoch 00004: val_loss improved from 9.34928 to 9.21944, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.8867 - acc: 0.4108 - val_loss: 9.2194 - val_acc: 0.3485
Epoch 6/20
6520/6680 [============================>.] - ETA: 0s - loss: 8.7824 - acc: 0.4250 Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 8.7592 - acc: 0.4257 - val_loss: 9.2725 - val_acc: 0.3533
Epoch 7/20
6560/6680 [============================>.] - ETA: 0s - loss: 8.6596 - acc: 0.4396Epoch 00006: val_loss improved from 9.21944 to 9.15489, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.6656 - acc: 0.4394 - val_loss: 9.1549 - val_acc: 0.3713
Epoch 8/20
6560/6680 [============================>.] - ETA: 0s - loss: 8.6309 - acc: 0.4450Epoch 00007: val_loss improved from 9.15489 to 9.11023, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.6193 - acc: 0.4457 - val_loss: 9.1102 - val_acc: 0.3725
Epoch 9/20
6660/6680 [============================>.] - ETA: 0s - loss: 8.5606 - acc: 0.4514Epoch 00008: val_loss improved from 9.11023 to 9.02983, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.5546 - acc: 0.4516 - val_loss: 9.0298 - val_acc: 0.3808
Epoch 10/20
6480/6680 [============================>.] - ETA: 0s - loss: 8.5193 - acc: 0.4596 Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 8.4864 - acc: 0.4614 - val_loss: 9.0344 - val_acc: 0.3808
Epoch 11/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.3184 - acc: 0.4634Epoch 00010: val_loss improved from 9.02983 to 8.85772, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.3317 - acc: 0.4627 - val_loss: 8.8577 - val_acc: 0.3904
Epoch 12/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.1942 - acc: 0.4735Epoch 00011: val_loss improved from 8.85772 to 8.81983, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.1865 - acc: 0.4740 - val_loss: 8.8198 - val_acc: 0.3820
Epoch 13/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.1238 - acc: 0.4824Epoch 00012: val_loss improved from 8.81983 to 8.74248, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.1118 - acc: 0.4831 - val_loss: 8.7425 - val_acc: 0.3940
Epoch 14/20
6640/6680 [============================>.] - ETA: 0s - loss: 7.8342 - acc: 0.4919Epoch 00013: val_loss improved from 8.74248 to 8.35885, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.8332 - acc: 0.4921 - val_loss: 8.3588 - val_acc: 0.4012
Epoch 15/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.5565 - acc: 0.5087Epoch 00014: val_loss improved from 8.35885 to 8.24128, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.5746 - acc: 0.5070 - val_loss: 8.2413 - val_acc: 0.4132
Epoch 16/20
6480/6680 [============================>.] - ETA: 0s - loss: 7.3949 - acc: 0.5177Epoch 00015: val_loss improved from 8.24128 to 8.05371, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.3999 - acc: 0.5177 - val_loss: 8.0537 - val_acc: 0.4359
Epoch 17/20
6580/6680 [============================>.] - ETA: 0s - loss: 7.2935 - acc: 0.5334 Epoch 00016: val_loss improved from 8.05371 to 8.02237, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.3110 - acc: 0.5323 - val_loss: 8.0224 - val_acc: 0.4395
Epoch 18/20
6520/6680 [============================>.] - ETA: 0s - loss: 7.2448 - acc: 0.5337Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 7.2417 - acc: 0.5340 - val_loss: 8.0903 - val_acc: 0.4383
Epoch 19/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.1712 - acc: 0.5423Epoch 00018: val_loss improved from 8.02237 to 7.97973, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.1642 - acc: 0.5428 - val_loss: 7.9797 - val_acc: 0.4455
Epoch 20/20
6500/6680 [============================>.] - ETA: 0s - loss: 7.0716 - acc: 0.5485Epoch 00019: val_loss improved from 7.97973 to 7.85229, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.0778 - acc: 0.5482 - val_loss: 7.8523 - val_acc: 0.4419
Out[24]:
<keras.callbacks.History at 0x120e86be0>

Load the Model with the Best Validation Loss

In [21]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [22]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 41.9856%

Predict Dog Breed with the Model

In [77]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [78]:
### TODO: Obtain bottleneck features from another pre-trained CNN.

bottleneck_features = np.load('bottleneck_features/DogXceptionData.npz')
train_Xception = bottleneck_features['train']
valid_Xception = bottleneck_features['valid']
test_Xception = bottleneck_features['test']

print(test_Xception.shape)
(836, 7, 7, 2048)

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

First of all, I tried all of the bottleneck features. They were all fast to train (roughly 1 minute on a CPU) and far superior (between 47% and 83.6%) to the earlier accuracies obtained. The best result was achieved by the bottleneck feature Xception, with 83.6% correct classifications, after roughly 2,5 min of training. This was later improved to roughly 85.4% through some minor changes, as explained below, with resulting increase in training time.

Given that we already have the trained bottleneck features imported, my idea was to just add the last layers on top of this. That's where the GlobalAveragePooling2D and Dense layers comes from. The input shape of the former needs to match the shape of the input data while the latter output needs to contain 133 different alternatives. However, I added a Dropout layer in between to decrease the risk of overfitting (I planned to run for more baches than before). Also, it seems that the GlobalAveragePooling2D and GlobalMaxPooling2D layers are the easiest ways to go from a 4D tensor to a 2D. A 2D tensor is needed for the softmax activation function to work. In the end, it seems that the differences in both training time and accuracy are very small between the two, but I stayed with the GlobalMaxPooling2D. Mainly because it was the last one I tried =), but it might have actually reached this accuracy in fewer epochs as well. (Edit afterwards: research seems to suggest that Max Pooling is the better one.)

I also tried a Flatten layer in combination with some Dense layers, with different kind of output shapes. However, the amount of parameters increased so much that I only completed a full run on Dense(64, activation='relu') with roughly 6.4x10^6 parameters. The training took roughly 10 times as long with a resulting ~25% in accuracy. These bad results had me leave this approach, they just didn't seem promising.

As of the compilation step, I choose the same loss function as before but another optimizer. The SGD optimizer, with a very small learning rate, was chosen rather than an adaptive learning rate optimizer. This is to make sure that the updates stay very small so that the previously learned features won't be lost. This, according to the source you provided.

Augment the Training Data

In [79]:
#from keras.preprocessing.image import ImageDataGenerator

#train_Xception_to_use = train_Xception
#valid_Xception_to_use = valid_Xception

# create and configure augmented image generator
#datagen_train = ImageDataGenerator(
#    rotation_range = 40,
#    width_shift_range=0.2,  # randomly shift images horizontally (20% of total width)
#    height_shift_range=0.2,  # randomly shift images vertically (20% of total height)
#    horizontal_flip=True) # randomly flip images horizontally

# create and configure augmented image generator
#datagen_valid = ImageDataGenerator(
#    width_shift_range=0.2,  # randomly shift images horizontally (20% of total width)
#    height_shift_range=0.2,  # randomly shift images vertically (20% of total height)
#    horizontal_flip=True) # randomly flip images horizontally

# fit augmented image generator on data
#datagen_train.fit(train_Xception_to_use)
#datagen_valid.fit(valid_Xception_to_use)
In [80]:
### TODO: Define your architecture.

Xception_model = Sequential()

#Xception_model.add(Flatten(input_shape=train_Xception.shape[1:]))
#Xception_model.add(Dense(64, activation='relu'))
#Xception_model.add(Dropout(0.5))
#Xception_model.add(Dense(133, activation='softmax'))

#Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:])) # (7, 7, 512)

Xception_model.add(GlobalMaxPooling2D(input_shape=train_Xception.shape[1:]))
Xception_model.add(Dropout(0.5))
Xception_model.add(Dense(133, activation='softmax'))

Xception_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_max_pooling2d_2 (Glob (None, 2048)              0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 2048)              0         
_________________________________________________________________
dense_5 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517.0
Trainable params: 272,517.0
Non-trainable params: 0.0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [81]:
### TODO: Compile the model.
from keras import optimizers

#Xception_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
Xception_model.compile(loss='categorical_crossentropy', 
                       optimizer = optimizers.SGD(lr=1e-4, momentum=0.9), 
                       metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [264]:
# Time the training
start = time.time()

### TODO: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Xception.hdf5', 
                               verbose=1, save_best_only=True)

Xception_model.fit(train_Xception, train_targets, 
          validation_data=(valid_Xception, valid_targets),
          epochs=100, batch_size=20, callbacks=[checkpointer], verbose=1)


# Print how long it took
end = time.time()
tt = end-start
print("\nTotal training time was {0:0.0f} min and {1:0.0f} s. ".format((tt-tt%60)/60, tt%60))
Train on 6680 samples, validate on 835 samples
Epoch 1/100
6620/6680 [============================>.] - ETA: 0s - loss: 6.0905 - acc: 0.0414       Epoch 00000: val_loss improved from inf to 3.29094, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 17s - loss: 6.0820 - acc: 0.0415 - val_loss: 3.2909 - val_acc: 0.2862
Epoch 2/100
6640/6680 [============================>.] - ETA: 0s - loss: 3.7871 - acc: 0.2099Epoch 00001: val_loss improved from 3.29094 to 1.86148, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 3.7802 - acc: 0.2111 - val_loss: 1.8615 - val_acc: 0.5868
Epoch 3/100
6660/6680 [============================>.] - ETA: 0s - loss: 2.5942 - acc: 0.3958Epoch 00002: val_loss improved from 1.86148 to 1.26806, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 6s - loss: 2.5941 - acc: 0.3960 - val_loss: 1.2681 - val_acc: 0.6850
Epoch 4/100
6600/6680 [============================>.] - ETA: 0s - loss: 1.9611 - acc: 0.5106Epoch 00003: val_loss improved from 1.26806 to 0.99299, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 5s - loss: 1.9559 - acc: 0.5117 - val_loss: 0.9930 - val_acc: 0.7341
Epoch 5/100
6640/6680 [============================>.] - ETA: 0s - loss: 1.6336 - acc: 0.5842Epoch 00004: val_loss improved from 0.99299 to 0.84352, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 6s - loss: 1.6331 - acc: 0.5838 - val_loss: 0.8435 - val_acc: 0.7605
Epoch 6/100
6660/6680 [============================>.] - ETA: 0s - loss: 1.4079 - acc: 0.6228Epoch 00005: val_loss improved from 0.84352 to 0.75707, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 6s - loss: 1.4068 - acc: 0.6232 - val_loss: 0.7571 - val_acc: 0.7749
Epoch 7/100
6640/6680 [============================>.] - ETA: 0s - loss: 1.3042 - acc: 0.6506Epoch 00006: val_loss improved from 0.75707 to 0.69039, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 6s - loss: 1.3023 - acc: 0.6512 - val_loss: 0.6904 - val_acc: 0.7928
Epoch 8/100
6640/6680 [============================>.] - ETA: 0s - loss: 1.1902 - acc: 0.6712Epoch 00007: val_loss improved from 0.69039 to 0.65286, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 8s - loss: 1.1897 - acc: 0.6716 - val_loss: 0.6529 - val_acc: 0.8048
Epoch 9/100
6620/6680 [============================>.] - ETA: 0s - loss: 1.1081 - acc: 0.6884Epoch 00008: val_loss improved from 0.65286 to 0.62036, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 8s - loss: 1.1042 - acc: 0.6894 - val_loss: 0.6204 - val_acc: 0.8036
Epoch 10/100
6640/6680 [============================>.] - ETA: 0s - loss: 1.0548 - acc: 0.7050Epoch 00009: val_loss improved from 0.62036 to 0.59610, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 11s - loss: 1.0553 - acc: 0.7046 - val_loss: 0.5961 - val_acc: 0.8036
Epoch 11/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.9997 - acc: 0.7157 Epoch 00010: val_loss improved from 0.59610 to 0.58012, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 12s - loss: 0.9986 - acc: 0.7157 - val_loss: 0.5801 - val_acc: 0.8168
Epoch 12/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.9457 - acc: 0.7264Epoch 00011: val_loss improved from 0.58012 to 0.56214, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 8s - loss: 0.9463 - acc: 0.7263 - val_loss: 0.5621 - val_acc: 0.8072
Epoch 13/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.9054 - acc: 0.7434Epoch 00012: val_loss improved from 0.56214 to 0.54961, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.9050 - acc: 0.7440 - val_loss: 0.5496 - val_acc: 0.8156
Epoch 14/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.8799 - acc: 0.7464Epoch 00013: val_loss improved from 0.54961 to 0.53469, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 8s - loss: 0.8795 - acc: 0.7463 - val_loss: 0.5347 - val_acc: 0.8299
Epoch 15/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.8422 - acc: 0.7511Epoch 00014: val_loss improved from 0.53469 to 0.52641, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.8422 - acc: 0.7513 - val_loss: 0.5264 - val_acc: 0.8263
Epoch 16/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.8130 - acc: 0.7614Epoch 00015: val_loss improved from 0.52641 to 0.51826, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.8122 - acc: 0.7620 - val_loss: 0.5183 - val_acc: 0.8335
Epoch 17/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.7822 - acc: 0.7701Epoch 00016: val_loss improved from 0.51826 to 0.51088, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 8s - loss: 0.7841 - acc: 0.7699 - val_loss: 0.5109 - val_acc: 0.8275
Epoch 18/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.7617 - acc: 0.7721Epoch 00017: val_loss improved from 0.51088 to 0.50687, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 8s - loss: 0.7612 - acc: 0.7723 - val_loss: 0.5069 - val_acc: 0.8335
Epoch 19/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.7160 - acc: 0.7843Epoch 00018: val_loss improved from 0.50687 to 0.49921, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.7157 - acc: 0.7846 - val_loss: 0.4992 - val_acc: 0.8347
Epoch 20/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.7263 - acc: 0.7816Epoch 00019: val_loss improved from 0.49921 to 0.49629, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 6s - loss: 0.7271 - acc: 0.7819 - val_loss: 0.4963 - val_acc: 0.8359
Epoch 21/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.6850 - acc: 0.7924Epoch 00020: val_loss improved from 0.49629 to 0.48937, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.6850 - acc: 0.7928 - val_loss: 0.4894 - val_acc: 0.8359
Epoch 22/100
6600/6680 [============================>.] - ETA: 0s - loss: 0.6918 - acc: 0.7842 Epoch 00021: val_loss improved from 0.48937 to 0.48134, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 8s - loss: 0.6902 - acc: 0.7849 - val_loss: 0.4813 - val_acc: 0.8335
Epoch 23/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.6399 - acc: 0.8071Epoch 00022: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.6411 - acc: 0.8063 - val_loss: 0.4835 - val_acc: 0.8383
Epoch 24/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.6417 - acc: 0.8079Epoch 00023: val_loss improved from 0.48134 to 0.47837, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.6419 - acc: 0.8079 - val_loss: 0.4784 - val_acc: 0.8407
Epoch 25/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.6401 - acc: 0.8041 Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.6399 - acc: 0.8040 - val_loss: 0.4794 - val_acc: 0.8383
Epoch 26/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.6076 - acc: 0.8098 Epoch 00025: val_loss improved from 0.47837 to 0.47546, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 8s - loss: 0.6064 - acc: 0.8100 - val_loss: 0.4755 - val_acc: 0.8395
Epoch 27/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.6236 - acc: 0.8104 Epoch 00026: val_loss improved from 0.47546 to 0.46616, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 8s - loss: 0.6214 - acc: 0.8111 - val_loss: 0.4662 - val_acc: 0.8431
Epoch 28/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.5978 - acc: 0.8153Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.5994 - acc: 0.8148 - val_loss: 0.4683 - val_acc: 0.8395
Epoch 29/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.5690 - acc: 0.8231Epoch 00028: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.5701 - acc: 0.8229 - val_loss: 0.4664 - val_acc: 0.8479
Epoch 30/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.5717 - acc: 0.8299Epoch 00029: val_loss improved from 0.46616 to 0.46577, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 6s - loss: 0.5711 - acc: 0.8299 - val_loss: 0.4658 - val_acc: 0.8431
Epoch 31/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.5608 - acc: 0.8289Epoch 00030: val_loss improved from 0.46577 to 0.46547, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.5599 - acc: 0.8293 - val_loss: 0.4655 - val_acc: 0.8407
Epoch 32/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.5484 - acc: 0.8311Epoch 00031: val_loss improved from 0.46547 to 0.45749, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.5476 - acc: 0.8313 - val_loss: 0.4575 - val_acc: 0.8527
Epoch 33/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.5476 - acc: 0.8330Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.5473 - acc: 0.8331 - val_loss: 0.4583 - val_acc: 0.8491
Epoch 34/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.5382 - acc: 0.8276 - ETA: 4s - loss: 0.5572 - acc: 0.8167Epoch 00033: val_loss improved from 0.45749 to 0.45682, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 8s - loss: 0.5377 - acc: 0.8278 - val_loss: 0.4568 - val_acc: 0.8479
Epoch 35/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.5428 - acc: 0.8318Epoch 00034: val_loss improved from 0.45682 to 0.45348, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.5426 - acc: 0.8319 - val_loss: 0.4535 - val_acc: 0.8479
Epoch 36/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.5187 - acc: 0.8306Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.5180 - acc: 0.8310 - val_loss: 0.4560 - val_acc: 0.8455
Epoch 37/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.5046 - acc: 0.8419Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.5044 - acc: 0.8415 - val_loss: 0.4569 - val_acc: 0.8455
Epoch 38/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.4969 - acc: 0.8396Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.4990 - acc: 0.8388 - val_loss: 0.4540 - val_acc: 0.8467
Epoch 39/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.4975 - acc: 0.8444Epoch 00038: val_loss improved from 0.45348 to 0.45266, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 9s - loss: 0.4972 - acc: 0.8445 - val_loss: 0.4527 - val_acc: 0.8503
Epoch 40/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.4930 - acc: 0.8389Epoch 00039: val_loss improved from 0.45266 to 0.45206, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.4935 - acc: 0.8388 - val_loss: 0.4521 - val_acc: 0.8455
Epoch 41/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.4897 - acc: 0.8441 - ETA: 8s - loss: 0.5160 - acc: 0.8289Epoch 00040: val_loss improved from 0.45206 to 0.44825, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 8s - loss: 0.4887 - acc: 0.8445 - val_loss: 0.4483 - val_acc: 0.8479
Epoch 42/100
6600/6680 [============================>.] - ETA: 0s - loss: 0.4846 - acc: 0.8438 Epoch 00041: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.4844 - acc: 0.8440 - val_loss: 0.4505 - val_acc: 0.8527
Epoch 43/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.4677 - acc: 0.8462Epoch 00042: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.4667 - acc: 0.8463 - val_loss: 0.4485 - val_acc: 0.8503
Epoch 44/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.4586 - acc: 0.8511 Epoch 00043: val_loss improved from 0.44825 to 0.44595, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.4584 - acc: 0.8507 - val_loss: 0.4459 - val_acc: 0.8539
Epoch 45/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.4653 - acc: 0.8485Epoch 00044: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.4638 - acc: 0.8488 - val_loss: 0.4517 - val_acc: 0.8503
Epoch 46/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.4420 - acc: 0.8613 - ETA: 4s - loss: 0.4388 - acc: 0.8613 - ETA: 0s - loss: 0.4474 - acc: 0.8602Epoch 00045: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.4414 - acc: 0.8615 - val_loss: 0.4475 - val_acc: 0.8551
Epoch 47/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.4394 - acc: 0.8609 - ETA: 2s - loss: 0.4437 - acc: 0.8596Epoch 00046: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.4388 - acc: 0.8609 - val_loss: 0.4529 - val_acc: 0.8539
Epoch 48/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.4235 - acc: 0.8582Epoch 00047: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.4250 - acc: 0.8579 - val_loss: 0.4517 - val_acc: 0.8527
Epoch 49/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.4435 - acc: 0.8566Epoch 00048: val_loss did not improve
6680/6680 [==============================] - 9s - loss: 0.4437 - acc: 0.8564 - val_loss: 0.4477 - val_acc: 0.8503
Epoch 50/100
6600/6680 [============================>.] - ETA: 0s - loss: 0.4276 - acc: 0.8611Epoch 00049: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.4273 - acc: 0.8611 - val_loss: 0.4484 - val_acc: 0.8539
Epoch 51/100
6600/6680 [============================>.] - ETA: 0s - loss: 0.4260 - acc: 0.8641Epoch 00050: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.4263 - acc: 0.8636 - val_loss: 0.4467 - val_acc: 0.8587
Epoch 52/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.4189 - acc: 0.8667Epoch 00051: val_loss improved from 0.44595 to 0.44392, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.4186 - acc: 0.8666 - val_loss: 0.4439 - val_acc: 0.8575
Epoch 53/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.4106 - acc: 0.8616 - ETA: 4s - loss: 0.3875 - acc: 0.8706Epoch 00052: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.4100 - acc: 0.8617 - val_loss: 0.4459 - val_acc: 0.8539
Epoch 54/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.3906 - acc: 0.8702 Epoch 00053: val_loss improved from 0.44392 to 0.44217, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.3896 - acc: 0.8707 - val_loss: 0.4422 - val_acc: 0.8515
Epoch 55/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.3908 - acc: 0.8711Epoch 00054: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.3913 - acc: 0.8705 - val_loss: 0.4433 - val_acc: 0.8599
Epoch 56/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.3783 - acc: 0.8754 Epoch 00055: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.3778 - acc: 0.8754 - val_loss: 0.4441 - val_acc: 0.8575
Epoch 57/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3761 - acc: 0.8754Epoch 00056: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.3758 - acc: 0.8754 - val_loss: 0.4463 - val_acc: 0.8575
Epoch 58/100
6600/6680 [============================>.] - ETA: 0s - loss: 0.3789 - acc: 0.8742Epoch 00057: val_loss improved from 0.44217 to 0.44140, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.3790 - acc: 0.8743 - val_loss: 0.4414 - val_acc: 0.8563
Epoch 59/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.3880 - acc: 0.8729Epoch 00058: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.3878 - acc: 0.8729 - val_loss: 0.4416 - val_acc: 0.8575
Epoch 60/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.3720 - acc: 0.8807 - ETA: 5s - loss: 0.3715 - acc: 0.8793Epoch 00059: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.3719 - acc: 0.8807 - val_loss: 0.4448 - val_acc: 0.8587
Epoch 61/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.3755 - acc: 0.8730Epoch 00060: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.3770 - acc: 0.8722 - val_loss: 0.4422 - val_acc: 0.8599
Epoch 62/100
6600/6680 [============================>.] - ETA: 0s - loss: 0.3670 - acc: 0.8779Epoch 00061: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.3676 - acc: 0.8777 - val_loss: 0.4436 - val_acc: 0.8515
Epoch 63/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.3764 - acc: 0.8748Epoch 00062: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.3772 - acc: 0.8744 - val_loss: 0.4453 - val_acc: 0.8587
Epoch 64/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.3578 - acc: 0.8828Epoch 00063: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.3574 - acc: 0.8831 - val_loss: 0.4419 - val_acc: 0.8599
Epoch 65/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3588 - acc: 0.8821Epoch 00064: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.3583 - acc: 0.8822 - val_loss: 0.4429 - val_acc: 0.8611
Epoch 66/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.3671 - acc: 0.8810Epoch 00065: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.3660 - acc: 0.8810 - val_loss: 0.4442 - val_acc: 0.8611
Epoch 67/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.3446 - acc: 0.8814Epoch 00066: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.3457 - acc: 0.8814 - val_loss: 0.4446 - val_acc: 0.8551
Epoch 68/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.3590 - acc: 0.8840Epoch 00067: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.3584 - acc: 0.8841 - val_loss: 0.4465 - val_acc: 0.8563
Epoch 69/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.3384 - acc: 0.8848Epoch 00068: val_loss improved from 0.44140 to 0.43923, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 6s - loss: 0.3396 - acc: 0.8844 - val_loss: 0.4392 - val_acc: 0.8647
Epoch 70/100
6600/6680 [============================>.] - ETA: 0s - loss: 0.3425 - acc: 0.8876Epoch 00069: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.3415 - acc: 0.8879 - val_loss: 0.4438 - val_acc: 0.8611
Epoch 71/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.3427 - acc: 0.8839Epoch 00070: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.3414 - acc: 0.8846 - val_loss: 0.4406 - val_acc: 0.8647
Epoch 72/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.3373 - acc: 0.8911 Epoch 00071: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.3370 - acc: 0.8913 - val_loss: 0.4400 - val_acc: 0.8587
Epoch 73/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.3224 - acc: 0.8932Epoch 00072: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.3224 - acc: 0.8933 - val_loss: 0.4420 - val_acc: 0.8587
Epoch 74/100
6600/6680 [============================>.] - ETA: 0s - loss: 0.3298 - acc: 0.8892  - ETA: 4s - loss: 0.3114 - acc: 0.8932Epoch 00073: val_loss improved from 0.43923 to 0.43796, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 8s - loss: 0.3305 - acc: 0.8892 - val_loss: 0.4380 - val_acc: 0.8623
Epoch 75/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.3218 - acc: 0.8934 Epoch 00074: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.3206 - acc: 0.8939 - val_loss: 0.4406 - val_acc: 0.8635
Epoch 76/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.3113 - acc: 0.8958Epoch 00075: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.3117 - acc: 0.8958 - val_loss: 0.4450 - val_acc: 0.8599
Epoch 77/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3203 - acc: 0.8911Epoch 00076: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.3201 - acc: 0.8913 - val_loss: 0.4451 - val_acc: 0.8611
Epoch 78/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3114 - acc: 0.8971Epoch 00077: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.3117 - acc: 0.8970 - val_loss: 0.4422 - val_acc: 0.8611
Epoch 79/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.3124 - acc: 0.8935Epoch 00078: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.3123 - acc: 0.8937 - val_loss: 0.4382 - val_acc: 0.8563
Epoch 80/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.3175 - acc: 0.8932Epoch 00079: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.3190 - acc: 0.8924 - val_loss: 0.4398 - val_acc: 0.8599
Epoch 81/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.3138 - acc: 0.8937Epoch 00080: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.3137 - acc: 0.8939 - val_loss: 0.4425 - val_acc: 0.8551
Epoch 82/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.2998 - acc: 0.9057Epoch 00081: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.2998 - acc: 0.9057 - val_loss: 0.4392 - val_acc: 0.8611
Epoch 83/100
6600/6680 [============================>.] - ETA: 0s - loss: 0.3029 - acc: 0.8976Epoch 00082: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.3027 - acc: 0.8979 - val_loss: 0.4406 - val_acc: 0.8587
Epoch 84/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.2977 - acc: 0.9003Epoch 00083: val_loss improved from 0.43796 to 0.43690, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 6s - loss: 0.2977 - acc: 0.9001 - val_loss: 0.4369 - val_acc: 0.8623
Epoch 85/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2926 - acc: 0.9024Epoch 00084: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.2921 - acc: 0.9027 - val_loss: 0.4405 - val_acc: 0.8623
Epoch 86/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.3057 - acc: 0.8949Epoch 00085: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.3055 - acc: 0.8948 - val_loss: 0.4398 - val_acc: 0.8575
Epoch 87/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2817 - acc: 0.9053 - ETA: 1s - loss: 0.2752 - acc: 0.9053Epoch 00086: val_loss improved from 0.43690 to 0.43670, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.2819 - acc: 0.9048 - val_loss: 0.4367 - val_acc: 0.8623
Epoch 88/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.2933 - acc: 0.9009 Epoch 00087: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.2931 - acc: 0.9010 - val_loss: 0.4424 - val_acc: 0.8599
Epoch 89/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.2796 - acc: 0.9041Epoch 00088: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.2801 - acc: 0.9040 - val_loss: 0.4379 - val_acc: 0.8611
Epoch 90/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.2898 - acc: 0.9039Epoch 00089: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.2889 - acc: 0.9042 - val_loss: 0.4389 - val_acc: 0.8635
Epoch 91/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.2748 - acc: 0.9069 Epoch 00090: val_loss did not improve
6680/6680 [==============================] - 8s - loss: 0.2758 - acc: 0.9066 - val_loss: 0.4387 - val_acc: 0.8635
Epoch 92/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.2763 - acc: 0.9050Epoch 00091: val_loss did not improve
6680/6680 [==============================] - 6s - loss: 0.2763 - acc: 0.9051 - val_loss: 0.4396 - val_acc: 0.8671
Epoch 93/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2818 - acc: 0.9060Epoch 00092: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.2820 - acc: 0.9060 - val_loss: 0.4396 - val_acc: 0.8611
Epoch 94/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.2765 - acc: 0.9072Epoch 00093: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.2764 - acc: 0.9070 - val_loss: 0.4392 - val_acc: 0.8623
Epoch 95/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.2738 - acc: 0.9080Epoch 00094: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.2736 - acc: 0.9081 - val_loss: 0.4436 - val_acc: 0.8623
Epoch 96/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.2776 - acc: 0.9063Epoch 00095: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.2767 - acc: 0.9067 - val_loss: 0.4405 - val_acc: 0.8623
Epoch 97/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.2573 - acc: 0.9108Epoch 00096: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.2578 - acc: 0.9105 - val_loss: 0.4430 - val_acc: 0.8635
Epoch 98/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.2673 - acc: 0.9078Epoch 00097: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.2667 - acc: 0.9079 - val_loss: 0.4393 - val_acc: 0.8611
Epoch 99/100
6620/6680 [============================>.] - ETA: 0s - loss: 0.2664 - acc: 0.9065Epoch 00098: val_loss improved from 0.43670 to 0.43430, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 7s - loss: 0.2660 - acc: 0.9064 - val_loss: 0.4343 - val_acc: 0.8623
Epoch 100/100
6640/6680 [============================>.] - ETA: 0s - loss: 0.2574 - acc: 0.9120Epoch 00099: val_loss did not improve
6680/6680 [==============================] - 7s - loss: 0.2570 - acc: 0.9121 - val_loss: 0.4347 - val_acc: 0.8623

Total training time was 12 min and 48 s. 

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [82]:
### TODO: Load the model weights with the best validation loss.
Xception_model.load_weights('saved_models/weights.best.Xception.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [83]:
### TODO: Calculate classification accuracy on the test dataset.

# get index of predicted dog breed for each image in test set
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) 
                           for feature in test_Xception]

# report test accuracy
test_accuracy = (100*np.sum(np.array(Xception_predictions)==np.argmax(test_targets, axis=1))/
                 len(Xception_predictions))
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 85.4067%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [159]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

def Xception_predict_breed(img_path):
    # extract bottleneck features
    Xception_bottleneck_feature = extract_Xception(path_to_tensor(img_path))
    
    # get the predicted vector
    predicted_vector = Xception_model.predict(Xception_bottleneck_feature)
    
    # return the predicted dog breed
    return dog_names[np.argmax(predicted_vector)]
    

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [166]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
# I have tried to display the predicted dog breed as well but without success. =(

def import_files():
    files_to_check = np.array(glob("images/check_this/*"))   # Make sure that the images are JPEG! 
    #files_to_check = np.array(glob("dogImages/valid/107.Norfolk_terrier"))
    #print(files_to_check)
    return files_to_check                                    # if not, the kernel will stop running.

def get_dog_breed_picture(breed):
    length = len(breed) 
    for item in glob("dogImages/valid/*/*"):
        print(item[-(length + 10): -10])
        if item[-(length + 10): -10] == breed:
            print(item)
            breed_pics = np.array(glob(item))
            breed_pic = cv2.imread(item)
            cv_rgb2 = cv2.cvtColor(item, cv2.COLOR_BGR2RGB)
            return cv_rgb2


def image_detector(file):
    # start by displaying the picture
    image = cv2.imread(file)
    cv_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  
    plt.figure()
    #plt.figure(figsize=(10, 10))
    #plt.subplot(2,2,1)
    plt.imshow(cv_rgb)
    plt.show()
    
    # return the breed
    breed = Xception_predict_breed(file)  
    
    # check whether the picture is a dog, human or neither
    if dog_detector(file):
        print("Dog breed: {0}".format(breed))
    elif face_detector(file, face_cascade):
        #dog_breed_pucture = get_dog_breed_picture(breed)
        #plt.subplot(2,2,2)
        #plt.imshow(dog_breed_pucture)
        print("Hey human!")
        print("You look like the dog breed: {0}".format(breed))
        print("Don't worry however, it's cute!")   
    else:
        print("It seems that I can't classify this picture.")

    
        
start = time.time()
  
    
images = import_files()
image_detector(images[0])  

end = time.time()
tt = end-start
print("\nTime to run the algorithm: {0:0.0f} min and {1:0.0f} s ".format((tt-tt%60)/60, tt%60))
Dog breed: Collie

Time to run the algorithm: 1 min and 29 s 

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

Well, it classifies 8 out of 10 pictures correct, so I'm quite happy (see the output down below). It has problems to classify the third to last picture as a human. Maybe it's because of the sunglasses, maybe for other reasons. Also, the last dog picture is wrongly classified as an American Foxhound when it's actually a Dachshund, if the source is correct. However they are two breeds very similar to each other. Also, it does a good job with the cat picture.

The dog breed classifier does it job well in roughly 85% of the times. It's more than acceptable, but maybe little less than I thought before starting the project. Something I'm less happy with is the speed of the algorithm, it takes way too long to classify each picture. I'm running on a normal macbook pro, so I won't be able to use the GPU during training, but during classifying that shouldn't make any difference. If I understand it correct. It's a quite fast laptop, so it makes me wonder if I can change the algorithm to make the process faster? One way would be to use the other face detector (face_cascade2), but I would have to pay in accuracy, also it wouldn't be relevant for the dog pictures.

(Question for the reviewer:) Is it supposed to be this slow?

Some improvements to make in order to increase the accuracy:

  • Augment the input data and let the model train on it as well. However, I tried this in the initial-from-scratch model without any obvious improvements. But in general, this wold be a valid approach.
  • Trying different architectures and fine tune the parameters would eventually most likely result in better performance as well. I've tried some ten different architectures, but the possible alternatives are so many that there are most likely many that outperforms the one I chose.
  • Use more training and validation data. We have in total 8351 dog and 13233 human images. It's a fairly small data set compared to the data that's actually out there and to the amount of data Google is training their algorithms on for example.
  • I would also make sure that the face detector alorithm takes into account face shapes in a larger extent to prevent the missclassified human.
In [167]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

for i in range(len(images)):
    image_detector(images[i])
    print("="*80)
    
    
Dog breed: Collie
================================================================================
Dog breed: German_shepherd_dog
================================================================================
Hey human!
You look like the dog breed: Chinese_shar-pei
Don't worry however, it's cute!
================================================================================
Hey human!
You look like the dog breed: Silky_terrier
Don't worry however, it's cute!
================================================================================
Dog breed: American_water_spaniel
================================================================================
Dog breed: Labrador_retriever
================================================================================
Dog breed: Boxer
================================================================================
Dog breed: Brittany
================================================================================
It seems that I can't classify this picture.
================================================================================
Dog breed: Curly-coated_retriever
================================================================================
Dog breed: Chihuahua
================================================================================
Dog breed: Finnish_spitz
================================================================================
Dog breed: Golden_retriever
================================================================================
Dog breed: Pekingese
================================================================================
Dog breed: German_shorthaired_pointer
================================================================================
Dog breed: Labrador_retriever
================================================================================
Dog breed: Leonberger
================================================================================
It seems that I can't classify this picture.
================================================================================
Dog breed: Alaskan_malamute
================================================================================
Dog breed: American_foxhound
================================================================================
Dog breed: Welsh_springer_spaniel
================================================================================
In [ ]: